﻿using LJLib.Tools.File;
using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace LJLib.LocalLog
{
    internal class LocalTraceListener : TraceListener
    {
#if !WindowsCE
        private HashSet<string> oldStack = new HashSet<string>();
#endif

        private object _syncRoot = new object();

        private ILogger _logger = null;
        public bool HasStack { get; set; }
        public LocalTraceListener(ILogger logger) { _logger = logger; }
        public override void Write(string message)
        {
            lock (_syncRoot)
            {
                if (_logger != null)
                {
                    try
                    {
                        if (HasStack) // 包含堆栈信息
                        {
#if !WindowsCE
                            var stack = (new StackTrace()).ToString();
                            var key = stack;
                            var index = message.IndexOf(": ");
                            if (index >= 0)
                            {
                                key += message.Substring(0, index);
                            }
                            if (!oldStack.Contains(key)) // 重复的堆栈信息不输出
                            {
                                oldStack.Add(key);
                                message += "\r\n" + stack;
                                _logger.WriteLog(message);
                            }
#endif
                        }
                        else // 不包含堆栈信息
                        {
                            _logger.WriteLog(message);
                        }
                    }
                    catch (Exception ex) { }
                }
            }
        }

        public override void WriteLine(string message)
        {
            Write(message);
        }
    }
}